﻿using YougeBookmark.DataAccess;
using YougeBookmark.Models;

namespace YougeBookmark.Business.Services;

/// <summary>
/// 书签业务服务类
/// </summary>
public class BookmarkService
{
    private readonly AppDbContext _context;

    public BookmarkService(AppDbContext context) => _context = context;

    /// <summary>
    /// 添加新书签
    /// </summary>
    /// <param name="bookmark">书签对象</param>
    public void AddBookmark(Bookmark bookmark)
    {
        // 数据验证
        if (string.IsNullOrWhiteSpace(bookmark.Url))
            throw new ArgumentException("URL不能为空");

        _context.Bookmarks.Add(bookmark);
        _context.SaveChanges();
    }

    /// <summary>
    /// 分页查询书签
    /// </summary>
    /// <param name="page">页码（从1开始）</param>
    /// <param name="pageSize">每页数量</param>
    /// <param name="start">开始时间</param>
    /// <param name="end">结束时间</param>
    /// <param name="tagIds">标签ID列表</param>
    /// <returns>（结果列表, 总记录数）</returns>
    public (List<Bookmark>, int) GetPaged(int page, int pageSize, DateTime? start, DateTime? end, List<int> tagIds)
    {
        // 基础查询
        var query = _context.Bookmarks.AsQueryable();

        // 时间范围过滤
        if (start.HasValue)
            query = query.Where(b => b.CreatedAt >= start);
        if (end.HasValue)
            query = query.Where(b => b.CreatedAt <= end.Value.AddDays(1));

        // 标签过滤（使用逗号分隔的字符串匹配）
        //if (tagIds.Any())
        //    query = query.Where(b => tagIds.Any(t => b.Tags.Split(',').Contains(t.ToString())));
        if (tagIds.Any())
        {
            // 将数字列表转换为字符串数组（提前处理）
            var tagStrings = tagIds.Select(t => t.ToString()).ToArray();

            // 构造动态表达式
            query = query.Where(b =>
                tagStrings.Any(t => ("," + b.Tags + ",").Contains("," + t + ","))
            );
        }


        // 分页处理
        var total = query.Count();
        var items = query.OrderByDescending(b => b.CreatedAt)
                        .Skip((page - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();

        return (items, total);
    }

    public Bookmark GetBookmarkById(int id)
    {
        return _context.Bookmarks.Find(id);
    }

    public void UpdateBookmark(Bookmark bookmark)
    {
        var existing = _context.Bookmarks.Find(bookmark.Id);
        if (existing == null) return;

        existing.Url = bookmark.Url;
        existing.Remark = bookmark.Remark;
        existing.Tags = bookmark.Tags;

        _context.SaveChanges();
    }


}